package com.yc.net;

import java.io.BufferedReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.URL;
import java.net.URLConnection;

public class Demo1 {
	
	public static void main(String[] args) throws IOException {
		
		InetAddress localhost = InetAddress.getLocalHost();
		System.out.println(localhost);
		
		InetAddress baidu = InetAddress.getByName("www.baidu.com");
		System.out.println(baidu);
		// DNS 域名解析服务器, 网络提供商
		
		boolean bool = baidu.isReachable(5000);  // 5000 超时时间
		
		System.out.println(bool);
		
		
		URL url = new URL("http://www.hyycinfo.com/index.html");
		System.out.println(url.getProtocol());
		System.out.println(url.getHost());
		System.out.println(url.getPath());
		
		// 打开连接 => TCP 连接 => 3次握手
		URLConnection conn = url.openConnection();
		// 字节输入流
		InputStream in = conn.getInputStream();
		
//		byte[] bytes = new byte[100];
//		int count;
//		while(  (  count = in.read(bytes) ) > -1  ) {
//			String s = new String(bytes, 0, count);
//			System.out.println(s);
//		}
		
//		try {
//			String line;
//			while( ( line = br.readLine() ) != null ) {
//				System.out.println(line);
//			}
//		} finally {
//			br.close();
//			in.close();
//		}
		
		// try (  资源会自动的关闭, 资源必须是实现 AutoCloseable  )
		
		try(		// 字节流转字符流
				InputStreamReader isr = new InputStreamReader(in, "utf-8");
				// 按行读取的流
				BufferedReader br = new BufferedReader(isr);
				FileWriter fw = new FileWriter("D:\\dev\\yc138\\0621\\index.html")) {
			String line;
			while( ( line = br.readLine() ) != null ) {
				System.out.println(line);
				line+="\r\n";
				fw.write(line, 0, line.length());
			}
		}
		
	}

}
